package com.taotao.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.CommonResult;
import com.taotao.common.Constants;
import com.taotao.common.ResultGenerator;
import com.taotao.common.model.PageInfoModel;
import com.taotao.pojo.TbUser;
import com.taotao.service.UserService;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String openregister() {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult register(@RequestBody TbUser user) {
		TbUser tbUser = userService.saveUser(user);
		// 自动登陆
		return loginUser(tbUser);
	}

	@RequestMapping("/loginpage")
	public String openloginpage(Model model) {
		// 使用Model传值到前端页面request域中
		PageInfoModel pageInfoModel = new PageInfoModel();
		pageInfoModel.setTitle("信息管理系统 - 登录");
		model.addAttribute(Constants.ATT_PAGEINFO, pageInfoModel);
		// 已经登录过，直接进入主页
		try {
			// 这里有bug，整个服务器重启后，会默认进这个handler，
			// 导致securityManager为null，所以加try避免
			if (isRelogin()) {
				// 如果已经登陆，无需重新登录，进入首页
				// 使用redirect:/是因为浏览器地址要改变
				return "redirect:/";
			}
		} catch (Exception e) {
		}
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult login(@RequestBody TbUser user) {
		return loginUser(user);
	}

	private CommonResult loginUser(TbUser user) {
		return shiroLogin(user); // 调用shiro的登陆验证
	}

	private CommonResult shiroLogin(TbUser user) {
		if (user == null) {
			return ResultGenerator.genFailResult("内部错误，请重试");
		}
		// 组装token，包括客户公司名称、简称、客户编号、用户名称；密码
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword().toCharArray(),
				null);
		// 记住这个登陆的信息
		token.setRememberMe(true);
		String msg;
		// shiro登陆验证
		try {
			SecurityUtils.getSubject().login(token);
			// 0 未授权 1 账号问题 2 密码错误 3 账号密码错误
		} catch (IncorrectCredentialsException e) {
			msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect";
			return ResultGenerator.genLoginResult0(msg, 2, null);
		} catch (ExcessiveAttemptsException e) {
			return ResultGenerator.genLoginResult0(e.getMessage(), 2, null);
		} catch (LockedAccountException e) {
			return ResultGenerator.genLoginResult0(e.getMessage(), 1, null);
		} catch (DisabledAccountException e) {
			msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
			return ResultGenerator.genLoginResult0(msg, 1, null);
		} catch (ExpiredCredentialsException e) {
			msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
			return ResultGenerator.genLoginResult0(msg, 1, null);
		} catch (UnknownAccountException e) {
			msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
			return ResultGenerator.genLoginResult0(msg, 1, null);
		} catch (UnauthorizedException e) {
			msg = "您没有得到相应的授权！" + e.getMessage();
			return ResultGenerator.genLoginResult0(msg, 1, null);
		} catch (AuthenticationException ex) {
			return ResultGenerator.genFailResult(ex.getMessage()); // 自定义报错信息
		} catch (Exception ex) {
			return ResultGenerator.genFailResult("内部错误，请重试");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("username", user.getUsername());
		return ResultGenerator.genSuccessResult(data);
	}

	private boolean isRelogin() {
		Subject us = SecurityUtils.getSubject();
		if (us != null && us.isAuthenticated()) {
			return true; // 参数未改变，无需重新登录，默认为已经登录成功
		}
		return false; // 需要重新登陆
	}

	/**
	 * 检查用户是不是唯一的
	 * 
	 * @param inputvalue
	 * @return
	 */
	@RequestMapping(value = "/oauth/checkUnique", method = RequestMethod.POST)
	@ResponseBody
	public Map checkUnique(String inputvalue) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		TbUser user = userService.getUserByOtherWay(inputvalue);
		// 用户不存在，校验有效
		if (user == null) {
			map.put("valid", true);
		} else {
			map.put("valid", false);
		}
		return map;
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	@RequestMapping("/logout")
	@ResponseBody
	private CommonResult logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return new CommonResult();
	}
}
